package com.example.pertecttime.tools;

import android.os.Build;
import android.support.annotation.RequiresApi;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by 半生瓜 on 2017/7/12.
 */

public class HttpURLTools {

    static String cookie;

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String sendPost(String url, byte[] params) throws IOException {
        InputStream inputStream = null;
        HttpURLConnection conn = null;
        OutputStream outputStream = null;
        String result = null;
        String jSONresult = null;
        try {


            URL linkUrl = new URL(url);
            conn = (HttpURLConnection) linkUrl.openConnection();

            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestMethod("POST");
            outputStream = conn.getOutputStream();
            outputStream.write(params);
            outputStream.flush();

            if (conn.getResponseCode() == 200) {

                inputStream = conn.getInputStream();
                result = HttpUtils.readMyInputStream(inputStream);
                JSONObject jsonData = new JSONObject(result);
                jSONresult = jsonData.getString("errorCode");
//                cookie=conn.getHeaderField("get_cookie");
//                JSONObject data=new JSONObject(jsonData.getString("errorCode"));


                System.out.print("-----------------------!!!!!!!!!!!!!!!" + jSONresult);

            }
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String cookieskey = "Set-Cookie";
                Map<String, List<String>> maps = conn.getHeaderFields();
                List<String> coolist = maps.get(cookieskey);
                Iterator<String> it = coolist.iterator();
                StringBuffer sbu = new StringBuffer();

//                sbu.append("JSESSIONID=default; ");
                while (it.hasNext()) {
                    sbu.append(it.next());
                }
                System.out.println(sbu.toString());
                cookie = sbu.toString();
            }//if  
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) outputStream.close();
            if (conn != null) conn.disconnect();
        }
        return jSONresult;
    }

    public static String getcookie() {
        cookie = cookie.substring(cookie.indexOf("JSESSIONID="), cookie.indexOf(";"));
        return cookie;
    }


}


